//
// Created by Administrator on 2020/1/6.
//

#include "NamedPipe.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

NamedPipe::NamedPipe(const std::string &name) {
    mName=name;
    const char* p_name=mName.c_str();
    unlink(p_name);//不知道有什么用
    int res= mkfifo(p_name,0777);
    if(res==0){//fail to create named pipe
        printf("[-] fail to create named pipe:%s\n",p_name);
        return;
    }
    int fd=open(p_name,O_RDWR);
    printf("[!] pipe fd:%d\n",fd);
    mPipeFD=fdopen(fd,"rwe");
    if(!mPipeFD){
        printf("[-] fail to open named pipe:%s\n",p_name);
        return;
    }
    printf("[+] named pipe:%s has been ready\n",p_name);
    mReady=true;
}

int NamedPipe::Write(const std::string &content) {
    const char* p_content=content.c_str();
    return fwrite(p_content,content.size(),1,mPipeFD);
}

int NamedPipe::Read(std::string &result) {
    result.clear();//确保重新读入
    char temp[1]={0};
    int length=0;
    while(fgets(temp, 1, mPipeFD)) {
        int len = strlen(temp);
        result.append(temp);
        length++;
    }
    return length;
}

void NamedPipe::Close() {
    int res=fclose(mPipeFD);
    printf("[!] fail to close named pipe:%s with ret:%d\n",mName.c_str(),res);
}

